<template>
	<view class="login-container">
		<!-- 顶部装饰元素 -->
		<view class="top-decoration"></view>
		
		<view class="login-content">
			<!-- Logo区域 -->
			<view class="logo-section">
				<image class="logo" src="/static/icons/logo.png" mode="aspectFit"></image>
				<text class="app-name">合一个</text>
				<text class="app-slogan">遇事不决，数象为引</text>
			</view>
			
			<!-- 登录表单 -->
			<view class="login-form">
				<!-- 手机号输入 -->
				<view class="input-wrapper">
					<input 
						class="login-input" 
						type="number" 
						v-model="phoneNumber" 
						placeholder="请输入手机号"
						maxlength="11"
					/>
				</view>
				
				<!-- 验证码输入 -->
				<view class="input-wrapper verify-code-wrapper">
					<input 
						class="login-input verify-code-input" 
						type="number" 
						v-model="verifyCode" 
						placeholder="请输入验证码"
						maxlength="6"
					/>
					<button 
						class="send-code-btn" 
						:class="{ disabled: sendCodeDisabled }"
						:disabled="sendCodeDisabled"
						@tap="sendVerificationCode"
					>
						{{ sendCodeText }}
					</button>
				</view>
				
				<!-- 登录按钮 -->
				<button 
					class="login-btn" 
					:class="{ disabled: !canLogin }"
					:disabled="!canLogin"
					@tap="handlePhoneLogin"
				>
					<text v-if="!loginLoading">登录</text>
					<text v-else>登录中...</text>
				</button>
			</view>
			
			<!-- 微信登录 -->
			<view class="wechat-login">
				<view class="divider">
					<view class="line"></view>
					<text class="divider-text">其他登录方式</text>
					<view class="line"></view>
				</view>
				<button class="wechat-btn" @tap="handleWechatLogin">
					<text class="wechat-icon">💬</text>
					<text class="wechat-text">微信快速登录</text>
				</button>
			</view>
			
			<!-- 协议 -->
			<view class="agreement">
				<text class="agreement-text">
					登录即表示同意
					<text class="agreement-link" @tap="showPrivacyPolicy">《隐私政策》</text>
					和
					<text class="agreement-link" @tap="showUserAgreement">《用户协议》</text>
				</text>
			</view>
		</view>
	</view>
</template>

<script>
import { LoginService } from '@/utils/login-service.js'
import apiService from '@/utils/api-service.js'

export default {
	name: 'NewLoginPage',
	components: {
	},
	data() {
		return {
			phoneNumber: '',
			verifyCode: '',
			sendCodeDisabled: false,
			sendCodeText: '获取验证码',
			loginLoading: false,
			wechatLoading: false,
			loginService: null,
			countdown: 0,
			countdownTimer: null
		}
	},
	computed: {
		canLogin() {
			return this.phoneNumber.length === 11 && this.verifyCode.length === 6 && !this.loginLoading
		}
	},
	onLoad() {
		this.loginService = new LoginService()
		
		// 检查是否已经登录
		if (this.loginService.isLoggedIn()) {
			this.navigateBack()
		}
	},
	onUnload() {
		// 清除定时器
		if (this.countdownTimer) {
			clearInterval(this.countdownTimer)
		}
	},
	methods: {
		/**
		 * 发送验证码
		 */
		async sendVerificationCode() {
			if (this.sendCodeDisabled) return
			
			// 验证手机号
			if (!this.phoneNumber || this.phoneNumber.length !== 11) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}
			
			this.sendCodeDisabled = true
			
			try {
				// 调用后端API发送验证码
				const response = await apiService.sendVerificationCode({
					phone: this.phoneNumber,
					type: 'LOGIN'
				})
				console.log('验证码发送成功:', response)
				
				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				})
				
				// 启动倒计时
				this.startCountdown()
			} catch (error) {
				console.error('验证码发送失败:', error)
				uni.showToast({
					title: error.message || '验证码发送失败',
					icon: 'none'
				})
				this.sendCodeDisabled = false
			}
		},
		
		/**
		 * 启动验证码倒计时
		 */
		startCountdown() {
			this.countdown = 60
			this.sendCodeText = `${this.countdown}s后重新获取`
			
			this.countdownTimer = setInterval(() => {
				this.countdown--
				this.sendCodeText = `${this.countdown}s后重新获取`
				
				if (this.countdown <= 0) {
					clearInterval(this.countdownTimer)
					this.countdownTimer = null
					this.sendCodeDisabled = false
					this.sendCodeText = '获取验证码'
				}
			}, 1000)
		},
		
		/**
		 * 手机号验证码登录
		 */
		async handlePhoneLogin() {
			if (!this.canLogin) return
			
			this.loginLoading = true
			
			try {
				// 调用登录服务进行手机号登录
				const userInfo = await this.loginService.phoneLogin(this.phoneNumber, this.verifyCode)
				console.log('登录成功:', userInfo)
				
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				})
				
				// 延迟跳转，让用户看到成功提示
				setTimeout(() => {
					this.navigateBack()
				}, 1500)
			} catch (error) {
				console.error('登录失败:', error)
				uni.showToast({
					title: error.message || '登录失败',
					icon: 'none'
				})
			} finally {
				this.loginLoading = false
			}
		},
		
		/**
		 * 微信登录
		 */
		async handleWechatLogin() {
			console.log('开始微信登录')
			this.wechatLoading = true
			
			try {
				// 先获取微信登录凭证
				const loginResult = await this.loginService.wechatLogin()
				console.log('微信登录凭证获取成功:', loginResult)
				
				// 调用后端API进行登录
				const response = await apiService.login({
					type: 'wechat',
					code: loginResult.code,
					userInfo: {
						nickName: loginResult.nickName,
						avatarUrl: loginResult.avatarUrl,
						gender: loginResult.gender,
						city: loginResult.city,
						province: loginResult.province,
						country: loginResult.country
					}
				})
				
				if (response.success) {
					// 保存token
					apiService.setToken(response.data.accessToken)
					
					// 保存用户信息
					const userInfo = {
						userId: response.data.userId,
						phoneNumber: response.data.userInfo.phone,
						nickName: response.data.userInfo.nickname,
						avatarUrl: response.data.userInfo.avatar,
						loginType: 'wechat',
						loginTime: new Date().getTime(),
						accessToken: response.data.accessToken,
						refreshToken: response.data.refreshToken
					}
					
					await this.loginService.saveUserInfo(userInfo)
					
					console.log('后端登录成功:', response.data)
					
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})
					
					// 延迟跳转，让用户看到成功提示
					setTimeout(() => {
						this.navigateBack()
					}, 1500)
				} else {
					throw new Error(response.message || '登录失败')
				}
				
			} catch (error) {
				console.error('微信登录失败:', error)
				uni.showToast({
					title: error.message || '登录失败',
					icon: 'none'
				})
			} finally {
				this.wechatLoading = false
			}
		},
		
		/**
		 * 显示隐私政策
		 */
		showPrivacyPolicy() {
			uni.showModal({
				title: '隐私政策',
				content: '我们重视您的隐私，会严格保护您的个人信息安全...',
				showCancel: false
			})
		},
		
		/**
		 * 显示用户协议
		 */
		showUserAgreement() {
			uni.showModal({
				title: '用户协议',
				content: '欢迎使用"合一个"应用，请仔细阅读本协议...',
				showCancel: false
			})
		},
		
		/**
		 * 返回上一页
		 */
		navigateBack() {
			// 如果是从其他页面跳转来的，返回上一页
			// 否则跳转到首页
			const pages = getCurrentPages()
			if (pages.length > 1) {
				uni.navigateBack()
			} else {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.login-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
	position: relative;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
}

.top-decoration {
	position: absolute;
	top: -100rpx;
	right: -100rpx;
	width: 300rpx;
	height: 300rpx;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.1);
}

.login-content {
	width: 90%;
	max-width: 600rpx;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 30rpx;
	padding: 80rpx 60rpx 60rpx;
	box-shadow: 0 20rpx 50rpx rgba(0, 0, 0, 0.1);
	position: relative;
	z-index: 2;
	margin: 40rpx 0;
}

.logo-section {
	text-align: center;
	margin-bottom: 60rpx;
	
	.logo {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 20rpx;
		border-radius: 25rpx;
		box-shadow: 0 10rpx 30rpx rgba(106, 130, 251, 0.2);
	}
	
	.app-name {
		display: block;
		font-size: 48rpx;
		font-weight: 700;
		color: #333;
		margin-bottom: 16rpx;
		letter-spacing: 2rpx;
	}
	
	.app-slogan {
		display: block;
		font-size: 28rpx;
		color: #6A82FB;
		font-weight: 300;
	}
}

.login-form {
	width: 100%;
	margin-bottom: 50rpx;
}

.input-wrapper {
	position: relative;
	margin-bottom: 30rpx;
	
	&.verify-code-wrapper {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}
	
	.login-input {
		width: 100%;
		height: 80rpx;
		padding: 0 30rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 16rpx;
		background: #fff;
		font-size: 30rpx;
		color: #333;
		box-sizing: border-box;
		transition: all 0.3s ease;
		
		&:focus {
			border-color: #6A82FB;
			box-shadow: 0 0 0 2rpx rgba(106, 130, 251, 0.2);
		}
		
		&.verify-code-input {
			flex: 1;
		}
		
		&::placeholder {
			color: #bbb;
		}
	}
	
	.send-code-btn {
		width: 180rpx;
		height: 80rpx;
		border: none;
		border-radius: 16rpx;
		background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
		color: white;
		font-size: 26rpx;
		font-weight: 500;
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.98);
		}
		
		&.disabled {
			background: #ccc;
		}
	}
}

.login-btn {
	width: 100%;
	height: 80rpx;
	border: none;
	border-radius: 16rpx;
	background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
	color: white;
	font-size: 32rpx;
	font-weight: 600;
	letter-spacing: 2rpx;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.98);
	}
	
	&.disabled {
		background: #ccc;
	}
}

.wechat-login {
	width: 100%;
	
	.divider {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		
		.line {
			flex: 1;
			height: 2rpx;
			background: #e0e0e0;
		}
		
		.divider-text {
			padding: 0 20rpx;
			font-size: 26rpx;
			color: #999;
		}
	}
	
	.wechat-btn {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #6A82FB;
		border-radius: 16rpx;
		background: transparent;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 20rpx;
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.98);
		}
		
		.wechat-icon {
			font-size: 36rpx;
		}
		
		.wechat-text {
			font-size: 30rpx;
			color: #6A82FB;
			font-weight: 500;
		}
	}
}

.agreement {
	margin-top: 50rpx;
	text-align: center;
	
	.agreement-text {
		font-size: 24rpx;
		color: #999;
		line-height: 1.6;
		
		.agreement-link {
			color: #6A82FB;
			text-decoration: underline;
		}
	}
}

// 响应式设计
@media (min-width: 768px) {
	.login-content {
		padding: 100rpx 80rpx 80rpx;
		max-width: 500rpx;
	}
	
	.logo-section {
		margin-bottom: 80rpx;
	}
	
	.app-name {
		font-size: 56rpx;
	}
	
	.app-slogan {
		font-size: 30rpx;
	}
}
</style>